#!/bin/sh

COREVER=$(cat /opt/pakfire/db/core/mine)
# FIXME: edit this lines before release
URL="http://download.ipfire.org/releases/ipfire-2.x/2.17-core$COREVER/"
ISO="ipfire-2.17.i586-full-core$COREVER.iso"

if [ -z $1 ]; then
	echo usage: $0 backup-file
	exit
fi

TS=$1

mkdir -p /var/tmp/backupiso
cd /var/tmp/backupiso

if [ ! -e ${ISO} ]
then
	echo "Fetching ${URL}${ISO}"
	wget --quiet -c ${URL}${ISO}
fi

echo "Fetching ${URL}${ISO}.md5"
wget --quiet -O ${ISO}.md5 ${URL}${ISO}.md5

echo "Checking md5 of ${ISO}"
md5sum --status -c ${ISO}.md5
if [ $? -eq 0 -o $? -eq 24 ]
then
	echo "md5 is OK"
else
	echo "md5 mismatch"
	echo "Fetching again ${URL}${ISO}"
	wget --quiet -O ${ISO} ${URL}${ISO}
	echo "Checking again md5 of ${ISO}"
	md5sum --status -c ${ISO}.md5
	if [ $? -eq 0 -o $? -eq 24 ]
	then
		echo "md5 is OK"
	else
		echo "md5 mismatch"
		echo "aborting backup because md5 mismatch"
		exit 1
	fi
fi
rm ${ISO}.md5

echo "Remastering iso"
mkdir -p backupiso.tmp.${TS}
mount -o loop ${ISO} backupiso.tmp.${TS}
cp -pr backupiso.tmp.${TS} backupiso.${TS}
umount backupiso.tmp.${TS}
rm -r backupiso.tmp.${TS}

# Copy backup file to disk
cp "/var/ipfire/backup/${TS}.ipf" "backupiso.${TS}/backup.ipf"

echo "Running mkisofs"
mkisofs -J -r -V "ipfire backup ${TS}" \
            -b boot/isolinux/isolinux.bin -no-emul-boot -boot-load-size 4 -boot-info-table \
            -c boot/isolinux/boot.catalog backupiso.${TS} > $(basename ${ISO} .iso)-${TS}.iso
isohybrid $(basename ${ISO} .iso)-${TS}.iso

echo "Cleaning up"
rm -rf backupiso.${TS}
